package com.cdyGateway.gatewayFilter;

import com.google.common.util.concurrent.RateLimiter;
import entity.Result;
import entity.StatusCode;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author ：cdy
 * @date ：Created in 2020/11/16 13:11
 * @description：www.cdyong.cn
 * 限流
 */
@Component
public class LimitFilter implements GlobalFilter, Ordered {

    //每秒创建2000个令牌
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(2000);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        if (!RATE_LIMITER.tryAcquire()) {
            //不存在，直接返回验证失败，让其重新登录
            ServerHttpResponse response = exchange.getResponse();
            Result result=  new Result(false, StatusCode.TOO_MANY_REQUESTS,"请求过多");

            byte[] bits = result.toString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -4;
    }
}
